<?php

namespace App\Models;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\ModelTree;
use Encore\Admin\Traits\AdminBuilder;

//商圈分类
class StoreCategory extends Model
{
    use ModelTree, AdminBuilder;

    protected $table = 'c_store_categories';

    protected $fillable = ['pid', 'name', 'sort'];

    protected $with = [
        'parent'
    ];
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->setParentColumn('pid');  // 父ID
        $this->setOrderColumn('sort'); // 排序
        $this->setTitleColumn('name'); // 标题
        $this->setParentColumn('pid');//删除使用的pid
    }
    /**
     * 该分类的子分类
     */
    public function child()
    {
        return $this->hasMany(get_class($this), 'pid', $this->getKeyName());
    }
    /**
     * 该分类的父分类
     */
    public function parent()
    {
        return $this->hasOne(get_class($this), $this->getKeyName(), 'pid');
    }
    public function getstoreCategory($param)
    {
        $where = [];
        $limit = 15;
        if (isset($param['pid'])) {
            $where[] = ['pid', '=', $param['pid']];
        }
        if (!empty($param['limit'])) {
            $limit = $param['limit'];
        }
        $res = $this::where($where)->skip(0)->take($limit)->get()->toArray();
//        $tree = (new Tool())::buildTree($res);
        $host = new Url();
        foreach ($res as $k => $v) {
            $res[$k]['image'] = $host::getHttpHost() . 'upload/' . $v['image'];
        }
        return $res;
    }

    public function getstoreCategoryAndroid($param)
    {
        $where = [];
        $limit = 50;
        if (isset($param['pid'])) {
            $where[] = ['pid', '=', $param['pid']];
        }
        if (!empty($param['limit'])) {
            $limit = $param['limit'];
        }
        $res = $this::where($where)->skip(0)->take($limit)->get()->toArray();
        $host = new Url();
        $i = 0;
        $list = [];
        $data = [];
        $end = count($res)-1;
        foreach ($res as $k => &$v) {
            $v['image'] = $host::getHttpHost() . 'upload/' . $v['image'];
            $data[] = $v;
            if ($i == 1 || $end == $k) {
                $list[] = $data;
                $data = [];
                $i = 0;
                continue;
            }
            $i++;
        }
        return $list;
    }

    /**
     * 更新
     * @param $id
     * @return mixed
     */
    public function getName($id)
    {
        return $this->where('id', $id)->value('name');
    }

    /**获取下拉列表
     * @return mixed
     */
    public function getOptions()
    {
        $options = $this->select('id', 'name as text')->get();
        $selectOption = [];
        foreach ($options as $option) {
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }
}
